﻿
using Base.Infrastructure.Dto.Request.Login;
using Base.Infrastructure.Dto.Response;
using Base.Infrastructure.EFCore.MySql;
using Base.Infrastructure.IOC;
using Base.Infrastructure.Tools;
using Base.Infrastructure.Tools.Attributes;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Base.Service.Instance
{
    [Inject]
    public class LoginService : BaseService, Base.Service.Interface.ILoginService

    {
        private readonly LoginIOC _loginIOC;
        private readonly IConfiguration _configuration;

        public LoginService(LoginIOC loginIOC, IConfiguration configuration)
        {
            _loginIOC = loginIOC;
            _configuration = configuration;
        }

        /// <summary>
        /// 登录方法
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ApiResult Logins(LoginRequestDto dto)
        {
            var ai = _loginIOC._loginService.QueryAll(d => d.Account == dto.account && d.Password == dto.password);
            if (ai.Any())
            {
                var user = ai.Single();
                string id = Config.GUID();
                this.AddLogsinfo(new Logsinfo
                {
                    Id = id,
                    Lid = user.Id,
                    Lcode = dto.code,
                    Lip = dto.ip,
                    LoginTime = DateTime.Now.ToString(),
                });

                //JWT加密
                //授权  登录成功后 生成一个有效的token
                var claims = new[]
                  {
                    new Claim(ClaimTypes.Name, dto.code),
                    new Claim(ClaimTypes.Role,"admin")
                };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecurityKey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                string jwtKey = _configuration["JWT:issuer"];
                var token = new JwtSecurityToken(
                    issuer: jwtKey,
                    audience: jwtKey,
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(60 * 12), //token 过期时间
                    signingCredentials: creds);
                var tokens = new { token = new JwtSecurityTokenHandler().WriteToken(token) };

                //成功后生成日志记录

                return GetResult(1, data: tokens);
            }
            return GetResult(-1, "账号密码错误");
        }

        /// <summary>
        /// 添加登录记录
        /// </summary>
        /// <returns></returns>
        private bool AddLogsinfo(Logsinfo logsinfo)
        {
            _loginIOC._logininfoService.Add(logsinfo);
            return _loginIOC._logininfoService.SaveChanges() > 0;
        }

        /// <summary>
        /// code验证是否登录
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public Login? CheckLogin(string code)
        {
            var ai = _loginIOC._logininfoService.QueryAll(d => d.Lcode == code);
            if (ai.Any())
            {
                var log = ai.Single();
                var lid = log.Lid;
                var logs = _loginIOC._logininfoService.QueryAll(out int total, 1, 1, o => o.LoginTime, false, d => d.Lid == lid).Single();
                if (logs.Lcode == code)
                {
                    var u = _loginIOC._loginService.QueryAll(d => d.Id == lid).Single();
                    return u;
                }
                else
                {
                    return null;
                }
            }
            //找不到code 验证失败
            return null;
        }
    }
}
